package util;

/**
 * 转类型工具类
 *
 * @Author: Crystal
 * @Date: 2018/11/27 17:51
 **/
public class CastUtil {
    /**
     * 转换为string
     *
     * @param obj
     * @return
     */
    public static String castString(Object obj) {
        return castString(obj, "");
    }

    /**
     * 转换为string
     *
     * @param obj
     * @param defaultValue 为空时,或转换失败,返回该值
     * @return
     */
    public static String castString(Object obj, String defaultValue) {
        return obj == null ? defaultValue : String.valueOf(obj);
    }

    public static double castDouble(Object obj) {
        return castDouble(obj, 0);
    }

    /**
     * 转换为 double
     *
     * @param obj
     * @param defaultValue 为空时,或转换失败,返回该值
     * @return
     */
    public static double castDouble(Object obj, double defaultValue) {
        double result = defaultValue;
        if (obj != null) {
            String strValue = castString(obj);
            if (StringUtil.isNotEmpty(strValue)) {
                try {
                    result = Double.parseDouble(strValue);
                } catch (NumberFormatException e) {
                    result = defaultValue;
                }
            }
        }
        return result;
    }

    public static long castLong(Object obj) {
        return castLong(obj, 0);
    }

    public static long castLong(Object obj, long defaultValue) {
        long result = defaultValue;
        if (obj != null) {
            String strValue = castString(obj);
            if (StringUtil.isNotEmpty(strValue)) {
                try {
                    result = Long.parseLong(strValue);
                } catch (NumberFormatException e) {
                    result = defaultValue;
                }
            }
        }
        return result;
    }

    public static int castInt(Object obj) {
        return castInt(obj, 0);
    }

    public static int castInt(Object obj, int defaultValue) {
        int result = defaultValue;
        if (obj != null) {
            String strValue = castString(obj);
            if (StringUtil.isNotEmpty(strValue)) {
                try {
                    result = Integer.parseInt(strValue);
                } catch (NumberFormatException e) {
                    result = defaultValue;
                }
            }
        }
        return result;
    }

    public static boolean castBoolean(Object obj) {
        return castBoolean(obj, false);
    }

    public static boolean castBoolean(Object obj, boolean defaultValue) {
        boolean result = defaultValue;
        if (obj != null) {
            String strValue = castString(obj);
            if (StringUtil.isNotEmpty(strValue)) {
                result = Boolean.parseBoolean(strValue);
            }
        }
        return result;
    }
}
